<?php
class Activate extends MY_Controller{

	function __construct(){
		parent::__construct();
	}

	/**
	 * $id|$old_email|$new_email|time()
	 */
	function upemail(){
		$code = $this->input->get('code',true);
		$this->load->helper('encrypt');
		$view_data['state'] = 1;
		$view_data['message'] = 'Email激活修改成功！';
		try{
			$code = _base64_decode(str_replace(' ','+',$code),md5($this->config->item('encryption_key')));
			$codes = explode('|', $code, 4);
			if(count($codes) == 4){
				$time = time() - $codes[3];
				if($time > 86400)
					throw new Exception('Email激活修改已过期！',-1);
				
				$this->load->model('account/ClientModel','',true);
				$client = $this->ClientModel->selectById($codes[0]);
				if(count($client) > 0){
					if($client['code'] != 1){
						throw new Exception('Email激活链接已失效！',-1);
					}else if($client['email'] == $codes[1]){
						$result = $this->ClientModel->update(array('clientid'=>$codes[0],'email'=>$codes[2],'code'=>0));
						if($result == 0)
							throw new Exception('服务器忙，稍后再试！',-1);
					}else{
						throw new Exception('Email激活修改失败，数据有误！',-1);
					}
				}else{
					throw new Exception('Email激活修改失败，数据有误！',-1);
				}
			}
		}catch(Exception $e){
			$view_data['state'] = 0;
			if($e->getCode() == -1)
				$view_data['message'] = $e->getMessage();
			else
				$view_data['message'] = 'Email激活修改失败！';
		}
		$this->_view('result',$view_data);
	}
	
	function _test(){
		
		$id = 2;
		$old_email = '6830383@qq.com';
		$new_email = '526968781@qq.com';
		
		$this->load->helper('encrypt');
		
		$data['name'] = '测试';
		$data['href'] = $this->config->site_url('activate/upemail').'?code='.
			_base64_encode($id.'|'.$old_email.'|'.$new_email.'|'.time(),md5($this->config->item('encryption_key')));
			
		$this->load->library('Template');
		echo $this->template->view('emails/upemail.php',$data,true);
	}
	
}